package com.wosiliujing.learning.gateway.event;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.wosiliujing.learning.constant.CacheConstants;
import com.wosiliujing.learning.gateway.vo.RouteDefinitionVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.sql.ResultSet;
import java.util.List;

/**
 * @author liujing
 * @Description: TODO
 * @date 2019/6/3011:09
 */
@Slf4j
@Component
@AllArgsConstructor
public class DynamicRouteInitEventListener implements ApplicationListener<DynamicRouteInitEvent> {

    private final JdbcTemplate jdbcTemplate;

    private final RedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(DynamicRouteInitEvent dynamicRouteInitEvent) {
       Boolean result = redisTemplate.delete(CacheConstants.ROUTE_KEY);
       log.info("清除路由缓存{}",result);
       String sql = "select * from sys_route_config where del_flag='0'";
        List<RouteDefinitionVo> routes = jdbcTemplate.query(sql,(ResultSet rs, int i) -> {
            RouteDefinitionVo routeDefinitionVo = new RouteDefinitionVo();
            routeDefinitionVo.setId(rs.getString("route_id"));
            routeDefinitionVo.setRouteName(rs.getString("route_name"));
            routeDefinitionVo.setUri(URI.create(rs.getString("url")));
            routeDefinitionVo.setOrder(rs.getInt("order"));
            JSONArray filterArray = JSONUtil.parseArray(rs.getString("filters"));
            routeDefinitionVo.setFilters(filterArray.toList(FilterDefinition.class));
            JSONArray predicateArray = JSONUtil.parseArray(rs.getString("predicates"));
            routeDefinitionVo.setPredicates(predicateArray.toList(PredicateDefinition.class));
            return  routeDefinitionVo;
        });
        routes.forEach(route -> {
            log.info("加载路由ID:{},{}",route.getId(),route);
            redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(RouteDefinitionVo.class));
            redisTemplate.opsForHash().put(CacheConstants.ROUTE_KEY,route.getId(),route);
        });
    }
}
